package com.gitee.wsl.scheduler.job.repository

import com.gitee.wsl.scheduler.job.bean.JobSettings
import com.gitee.wsl.scheduler.job.bean.JobStatus
import com.gitee.wsl.scheduler.job.bean.ScheduledJob
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.singleOrNull
import kotlin.time.ExperimentalTime
import kotlin.time.Instant
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid


interface JobRepository {

    suspend fun exist(jobId: String): Boolean

    @OptIn(ExperimentalTime::class)
    suspend fun save(jobSettings: JobSettings, runAt: Instant?): ScheduledJob

    suspend fun get(id: String): ScheduledJob?

    @OptIn(ExperimentalUuidApi::class)
    suspend fun update(id: String, oldKjobId: Uuid?, kjobId: Uuid?, status: JobStatus, statusMessage: String?, retries: Int): Boolean

    @OptIn(ExperimentalUuidApi::class)
    suspend fun reset(id: String, oldKjobId: Uuid?): Boolean

    suspend fun startProgress(id: String): Boolean

    suspend fun completeProgress(id: String): Boolean

    suspend fun stepProgress(id: String, step: Long = 1): Boolean

    suspend fun setProgressMax(id: String, max: Long): Boolean

    suspend fun findNext(names: Set<String>, status: Set<JobStatus>, limit: Int): Flow<ScheduledJob>

    suspend fun findNextOne(names: Set<String>, status: Set<JobStatus>): ScheduledJob? =
        findNext(names, status, 1).singleOrNull()

    companion object
}